package com.laundry.shared.api

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.util.*

/**
 * 多端对接API管理器
 */
class MultiPlatformApiManager {
    
    companion object {
        private const val BASE_URL = "https://api.laundry.com/v1/"
        private const val WEBSOCKET_URL = "wss://ws.laundry.com/v1/"
    }
    
    /**
     * 用户端API接口
     */
    interface UserApiService {
        
        // 用户认证
        suspend fun login(request: LoginRequest): ApiResponse<LoginResponse>
        suspend fun register(request: RegisterRequest): ApiResponse<RegisterResponse>
        suspend fun refreshToken(token: String): ApiResponse<TokenResponse>
        suspend fun logout(userId: String): ApiResponse<Unit>
        
        // 用户信息
        suspend fun getUserProfile(userId: String): ApiResponse<UserProfile>
        suspend fun updateUserProfile(userId: String, profile: UserProfile): ApiResponse<UserProfile>
        suspend fun uploadAvatar(userId: String, imageData: ByteArray): ApiResponse<String>
        
        // 服务相关
        suspend fun getServices(filter: ServiceFilter): ApiResponse<ServiceListResponse>
        suspend fun getServiceDetail(serviceId: String): ApiResponse<ServiceDetail>
        suspend fun searchServices(query: SearchQuery): ApiResponse<SearchResult>
        suspend fun getNearbyMerchants(location: LocationData, radius: Double): ApiResponse<List<MerchantInfo>>
        
        // 订单管理
        suspend fun createOrder(order: CreateOrderRequest): ApiResponse<OrderResponse>
        suspend fun getOrders(userId: String, status: String?, page: Int): ApiResponse<OrderListResponse>
        suspend fun getOrderDetail(orderId: String): ApiResponse<OrderDetail>
        suspend fun cancelOrder(orderId: String, reason: String): ApiResponse<Unit>
        suspend fun confirmOrder(orderId: String): ApiResponse<Unit>
        suspend fun rateOrder(orderId: String, rating: OrderRating): ApiResponse<Unit>
        
        // 支付相关
        suspend fun createPayment(paymentRequest: PaymentRequest): ApiResponse<PaymentResponse>
        suspend fun getPaymentStatus(paymentId: String): ApiResponse<PaymentStatus>
        suspend fun getPaymentMethods(userId: String): ApiResponse<List<PaymentMethod>>
        
        // 积分会员
        suspend fun getPointsInfo(userId: String): ApiResponse<PointsInfo>
        suspend fun getMembershipInfo(userId: String): ApiResponse<MembershipInfo>
        suspend fun dailySignIn(userId: String): ApiResponse<SignInResult>
        suspend fun exchangePoints(userId: String, exchange: PointsExchange): ApiResponse<ExchangeResult>
        
        // 优惠券
        suspend fun getCoupons(userId: String): ApiResponse<List<UserCoupon>>
        suspend fun receiveCoupon(userId: String, couponId: String): ApiResponse<Unit>
        suspend fun useCoupon(userId: String, couponId: String, orderId: String): ApiResponse<Unit>
        
        // 地址管理
        suspend fun getAddresses(userId: String): ApiResponse<List<UserAddress>>
        suspend fun addAddress(userId: String, address: UserAddress): ApiResponse<UserAddress>
        suspend fun updateAddress(addressId: String, address: UserAddress): ApiResponse<UserAddress>
        suspend fun deleteAddress(addressId: String): ApiResponse<Unit>
        
        // 客服相关
        suspend fun createServiceSession(request: ServiceSessionRequest): ApiResponse<ServiceSession>
        suspend fun sendMessage(sessionId: String, message: ServiceMessage): ApiResponse<Unit>
        suspend fun getSessionHistory(sessionId: String): ApiResponse<List<ServiceMessage>>
        suspend fun getFAQs(category: String?): ApiResponse<List<FAQ>>
        
        // 消息通知
        suspend fun getNotifications(userId: String, page: Int): ApiResponse<NotificationListResponse>
        suspend fun markNotificationRead(notificationId: String): ApiResponse<Unit>
        suspend fun updateNotificationSettings(userId: String, settings: NotificationSettings): ApiResponse<Unit>
    }
    
    /**
     * 商家端API接口
     */
    interface MerchantApiService {
        
        // 商家认证
        suspend fun merchantLogin(request: MerchantLoginRequest): ApiResponse<MerchantLoginResponse>
        suspend fun merchantRegister(request: MerchantRegisterRequest): ApiResponse<MerchantRegisterResponse>
        suspend fun submitQualification(merchantId: String, qualification: MerchantQualification): ApiResponse<Unit>
        
        // 商家信息
        suspend fun getMerchantProfile(merchantId: String): ApiResponse<MerchantProfile>
        suspend fun updateMerchantProfile(merchantId: String, profile: MerchantProfile): ApiResponse<MerchantProfile>
        suspend fun uploadBusinessLicense(merchantId: String, imageData: ByteArray): ApiResponse<String>
        
        // 服务管理
        suspend fun getMerchantServices(merchantId: String): ApiResponse<List<MerchantService>>
        suspend fun addService(service: MerchantService): ApiResponse<MerchantService>
        suspend fun updateService(service: MerchantService): ApiResponse<MerchantService>
        suspend fun toggleServiceStatus(serviceId: String, isActive: Boolean): ApiResponse<Unit>
        suspend fun deleteService(serviceId: String, reason: String): ApiResponse<Unit>
        
        // 订单处理
        suspend fun getMerchantOrders(merchantId: String, status: String?, page: Int): ApiResponse<OrderListResponse>
        suspend fun acceptOrder(orderId: String): ApiResponse<Unit>
        suspend fun rejectOrder(orderId: String, reason: String): ApiResponse<Unit>
        suspend fun updateOrderStatus(orderId: String, status: String, notes: String?): ApiResponse<Unit>
        suspend fun uploadOrderImages(orderId: String, images: List<ByteArray>): ApiResponse<List<String>>
        
        // 财务管理
        suspend fun getFinancialSummary(merchantId: String, period: String): ApiResponse<FinancialSummary>
        suspend fun getTransactionHistory(merchantId: String, page: Int): ApiResponse<TransactionListResponse>
        suspend fun requestWithdrawal(merchantId: String, request: WithdrawalRequest): ApiResponse<WithdrawalResponse>
        
        // 保证金管理
        suspend fun getDepositInfo(merchantId: String): ApiResponse<DepositInfo>
        suspend fun payDeposit(merchantId: String, amount: Double, paymentMethod: String): ApiResponse<DepositRecord>
        suspend fun requestDepositRefund(merchantId: String, request: RefundRequest): ApiResponse<RefundRequest>
        
        // 违规管理
        suspend fun getViolations(merchantId: String, page: Int): ApiResponse<List<ViolationRecord>>
        suspend fun submitAppeal(reportId: String, appeal: ViolationAppeal): ApiResponse<ViolationAppeal>
        
        // 数据统计
        suspend fun getBusinessStatistics(merchantId: String, period: String): ApiResponse<BusinessStatistics>
        suspend fun getServicePerformance(merchantId: String, serviceId: String): ApiResponse<ServicePerformance>
        
        // 合同管理
        suspend fun getContracts(merchantId: String): ApiResponse<List<Contract>>
        suspend fun signContract(contractId: String, signature: DigitalSignature): ApiResponse<ContractSignature>
        suspend fun requestContractRenewal(contractId: String, terms: ContractTerms?): ApiResponse<Contract>
    }
    
    /**
     * 管理端API接口
     */
    interface AdminApiService {
        
        // 管理员认证
        suspend fun adminLogin(request: AdminLoginRequest): ApiResponse<AdminLoginResponse>
        suspend fun getAdminProfile(adminId: String): ApiResponse<AdminProfile>
        
        // 用户管理
        suspend fun getUsers(filter: UserFilter, page: Int): ApiResponse<UserListResponse>
        suspend fun getUserDetail(userId: String): ApiResponse<UserDetail>
        suspend fun updateUserStatus(userId: String, status: String, reason: String): ApiResponse<Unit>
        suspend fun resetUserPassword(userId: String): ApiResponse<String>
        
        // 商家管理
        suspend fun getMerchants(filter: MerchantFilter, page: Int): ApiResponse<MerchantListResponse>
        suspend fun getMerchantDetail(merchantId: String): ApiResponse<MerchantDetail>
        suspend fun reviewMerchantApplication(applicationId: String, decision: ReviewDecision): ApiResponse<Unit>
        suspend fun updateMerchantStatus(merchantId: String, status: String, reason: String): ApiResponse<Unit>
        
        // 订单监控
        suspend fun getOrderStatistics(period: String): ApiResponse<OrderStatistics>
        suspend fun getOrderDetail(orderId: String): ApiResponse<OrderDetail>
        suspend fun interveneOrder(orderId: String, action: InterventionAction): ApiResponse<Unit>
        
        // 违规处理
        suspend fun getViolationReports(filter: ViolationFilter, page: Int): ApiResponse<ViolationListResponse>
        suspend fun processViolation(reportId: String, decision: ViolationDecision): ApiResponse<ViolationProcessResult>
        suspend fun processAppeal(appealId: String, decision: AppealDecision): ApiResponse<AppealResult>
        
        // 财务管理
        suspend fun getPlatformFinancials(period: String): ApiResponse<PlatformFinancials>
        suspend fun processWithdrawal(withdrawalId: String, decision: WithdrawalDecision): ApiResponse<Unit>
        suspend fun adjustMerchantBalance(merchantId: String, adjustment: BalanceAdjustment): ApiResponse<Unit>
        
        // 系统配置
        suspend fun getSystemConfig(): ApiResponse<SystemConfig>
        suspend fun updateSystemConfig(config: SystemConfig): ApiResponse<Unit>
        suspend fun getAuditLogs(filter: AuditLogFilter, page: Int): ApiResponse<AuditLogListResponse>
        
        // 内容管理
        suspend fun getAnnouncements(page: Int): ApiResponse<AnnouncementListResponse>
        suspend fun createAnnouncement(announcement: Announcement): ApiResponse<Announcement>
        suspend fun updateAnnouncement(announcementId: String, announcement: Announcement): ApiResponse<Announcement>
        suspend fun deleteAnnouncement(announcementId: String): ApiResponse<Unit>
        
        // 数据分析
        suspend fun getPlatformStatistics(period: String): ApiResponse<PlatformStatistics>
        suspend fun getUserAnalytics(period: String): ApiResponse<UserAnalytics>
        suspend fun getMerchantAnalytics(period: String): ApiResponse<MerchantAnalytics>
        suspend fun getRevenueAnalytics(period: String): ApiResponse<RevenueAnalytics>
    }
    
    /**
     * 小程序端API接口
     */
    interface MiniProgramApiService {
        
        // 微信小程序专用接口
        suspend fun wechatLogin(code: String, userInfo: WechatUserInfo): ApiResponse<LoginResponse>
        suspend fun bindPhone(userId: String, phoneNumber: String, code: String): ApiResponse<Unit>
        suspend fun getWechatPayParams(orderId: String): ApiResponse<WechatPayParams>
        
        // 支付宝小程序专用接口
        suspend fun alipayLogin(authCode: String, userInfo: AlipayUserInfo): ApiResponse<LoginResponse>
        suspend fun getAlipayParams(orderId: String): ApiResponse<AlipayParams>
        
        // 小程序通用接口
        suspend fun getMiniProgramConfig(): ApiResponse<MiniProgramConfig>
        suspend fun reportMiniProgramEvent(event: MiniProgramEvent): ApiResponse<Unit>
        suspend fun getMiniProgramQRCode(scene: String, page: String): ApiResponse<String>
    }
    
    /**
     * Web端API接口
     */
    interface WebApiService {
        
        // Web端专用接口
        suspend fun webLogin(request: WebLoginRequest): ApiResponse<WebLoginResponse>
        suspend fun getWebConfig(): ApiResponse<WebConfig>
        suspend fun uploadFile(file: FileUploadRequest): ApiResponse<FileUploadResponse>
        suspend fun exportData(request: DataExportRequest): ApiResponse<DataExportResponse>
        
        // 批量操作接口
        suspend fun batchUpdateOrders(updates: List<OrderUpdate>): ApiResponse<BatchUpdateResult>
        suspend fun batchUpdateUsers(updates: List<UserUpdate>): ApiResponse<BatchUpdateResult>
        suspend fun batchUpdateMerchants(updates: List<MerchantUpdate>): ApiResponse<BatchUpdateResult>
        
        // 高级查询接口
        suspend fun advancedSearch(query: AdvancedSearchQuery): ApiResponse<AdvancedSearchResult>
        suspend fun generateReport(request: ReportRequest): ApiResponse<ReportResponse>
        suspend fun scheduleTask(task: ScheduledTask): ApiResponse<TaskResponse>
    }
}

/**
 * API响应基础类
 */
data class ApiResponse<T>(
    val code: Int,
    val message: String,
    val data: T?,
    val timestamp: Long = System.currentTimeMillis(),
    val requestId: String = UUID.randomUUID().toString()
) {
    val isSuccess: Boolean get() = code == 200
    val isError: Boolean get() = code != 200
}

/**
 * 分页响应
 */
data class PagedResponse<T>(
    val items: List<T>,
    val page: Int,
    val pageSize: Int,
    val totalCount: Int,
    val totalPages: Int,
    val hasNext: Boolean,
    val hasPrevious: Boolean
)

/**
 * WebSocket消息类型
 */
enum class WebSocketMessageType {
    ORDER_UPDATE,           // 订单状态更新
    NEW_MESSAGE,           // 新消息
    SYSTEM_NOTIFICATION,   // 系统通知
    REAL_TIME_DATA,       // 实时数据
    HEARTBEAT,            // 心跳
    ERROR                 // 错误消息
}

/**
 * WebSocket消息
 */
data class WebSocketMessage(
    val type: WebSocketMessageType,
    val data: Any,
    val timestamp: Long = System.currentTimeMillis(),
    val messageId: String = UUID.randomUUID().toString()
)

/**
 * 平台类型
 */
enum class PlatformType {
    ANDROID,        // Android应用
    IOS,           // iOS应用
    WEB,           // Web网站
    WECHAT_MINI,   // 微信小程序
    ALIPAY_MINI,   // 支付宝小程序
    H5             // H5页面
}
